package zuk.clipvietfun.likeandhistory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONObject;

import zuk.clipvietfun.R;
import zuk.clipvietfun.clip.Clip;
import zuk.clipvietfun.plus.DirAndFile;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

public class Like {
	Context context;
	public Like(FragmentActivity activity) {
		this.context = (Context) activity;
	}

	public Like(Context context) {
		this.context = context;
	}

	public void addLike(Clip video,boolean falseIsDef) {
		try {
			if(isHas(video))
				return;
			JSONArray jSonLike;
			if(!falseIsDef){
				jSonLike = loadLike();
			}else{
				jSonLike = new JSONArray();
			}
			JSONObject lItem = new JSONObject();
			lItem.put("Url", video.getId());
			lItem.put("ThumbImg", video.getImgurl());
			lItem.put("Tittle", video.getTitle());
			lItem.put("UTube", video.getuTube());
			jSonLike.put(lItem);
			saveLike(jSonLike);
			Toast.makeText(context, R.string.addlike, Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			addLike(video,true);
		}
	}

	public void removeLike(Clip video) {
		try {
			JSONArray jSonLike = loadLike();
			JSONArray jSonLikeRemoved = new JSONArray();
			for(int i=0;i<jSonLike.length();i++){
				JSONObject lItem = jSonLike.getJSONObject(i);
				if(!lItem.getString("UTube").equals(video.getuTube())){
					jSonLikeRemoved.put(lItem);
				}
			}
			Toast.makeText(context, R.string.removelike, Toast.LENGTH_SHORT).show();
			saveLike(jSonLikeRemoved);
		} catch (Exception e) {
		}
	}


	public boolean isHas(Clip video) {
		try {
			JSONArray jSonLike = loadLike();
			for(int i = 0; i < jSonLike.length();i++){
				JSONObject lItem = jSonLike.getJSONObject(i);

				if(lItem.getString("UTube").equals(video.getuTube())){
					return true;
				}
			}
			return false;
		} catch (Exception e) {

		}
		return false;
	}

	public boolean saveLike(JSONArray jSonLike) {
		try {
			File dirLike = new DirAndFile().makeDirLike(context);
			File fileLike = new DirAndFile().makeFileLike(dirLike);
			OutputStream fOut = new FileOutputStream(fileLike);
			byte[] bData = jSonLike.toString().getBytes();
			fOut.write(bData);
			fOut.flush();
			fOut.close();
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	public JSONArray loadLike() {
		try {
			File dirLike = new DirAndFile().makeDirLike(context);
			File fileLike = new DirAndFile().makeFileLike(dirLike);
			FileInputStream fis = new FileInputStream(fileLike);
			String data = new Scanner(fis,"UTF-8").useDelimiter("\\A").next();
			JSONArray jSonLike = new JSONArray(data);
			return jSonLike;
		} catch (Exception e) {
		}
		return null;
	}
}
